import { Input, message, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

import type { InputRef } from 'antd/es/input';

import './styles/tag-input.scss'; // 自定义样式

const { TextArea } = Input;

interface Props {
  onChange: (tags: (string | number)[]) => void;
  defaultTags?: (string | number)[];
  className?: string;
  placeholder?: string;
  warningMessage?: string;
  minRows?: number;
  maxLength?: number;
  showCount?: boolean;
  tagType?: string;
}

const TagInput = ({
  onChange,
  defaultTags = [],
  className = 'h-[200px]',
  placeholder = '输入文本并按回车',
  warningMessage = '标签已存在',
  minRows = 3,
  maxLength,
  showCount = false,
  tagType = 'string',
}: Props) => {
  const [inputValue, setInputValue] = useState<string>('');
  const [tags, setTags] = useState<(string | number)[]>([]);
  const [editingTag, setEditingTag] = useState<{ index: number; value: string } | null>(null);
  const editInputRef = useRef<InputRef>(null);
  const textAreaRef = useRef<HTMLTextAreaElement>(null);

  const validateInputValue = (value: string): boolean => {
    if (tagType === 'number') {
      const numValue = Number(value);
      return !Number.isNaN(numValue) && Number.isFinite(numValue);
    }
    return value.trim().length > 0;
  };

  const convertValue = (value: string): string | number => {
    if (tagType === 'number') {
      return Number(value);
    }
    return value;
  };

  // 处理输入框内容变化
  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setInputValue(e.target.value);
  };

  // 按下回车或失去焦点时添加标签
  const handleInputConfirm = () => {
    const trimmedValue = inputValue.trim();
    if (!trimmedValue) {
      return;
    }
    if (!validateInputValue(trimmedValue)) {
      if (tagType === 'number') {
        message.warning('请输入有效的数字');
      } else {
        message.warning('请输入有效的内容');
      }
      return;
    }

    const convertedValue = convertValue(trimmedValue);
    if (inputValue.trim() && !tags.includes(convertedValue)) {
      setTags([...tags, convertedValue]);
      setInputValue('');
    } else if (inputValue.trim()) {
      message.warning(warningMessage);
    }
  };

  // 处理 TextArea 的键盘事件
  const handleTextAreaKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault(); // 阻止默认换行行为
      handleInputConfirm();
    }
  };

  // 处理 TextArea 的失焦事件
  const handleTextAreaBlur = () => {
    handleInputConfirm();
  };

  // 删除标签
  const handleTagClose = (removedTag: string) => {
    const newTags = tags.filter((tag) => tag !== removedTag);
    setTags(newTags);
  };

  // 点击标签进入编辑模式
  const handleTagClick = (index: number, value: string) => {
    setEditingTag({ index, value });
  };

  // 保存修改（按下回车或失去焦点时）
  const handleEditConfirm = (value: string) => {
    if (!value.trim()) {
      // message.warning('标签内容不能为空');
      setEditingTag(null);
      handleTagClose(editingTag?.value || '');
      return;
    }
    if (!validateInputValue(value.trim())) {
      if (tagType === 'number') {
        message.warning('请输入有效的数字');
      } else {
        message.warning('请输入有效的内容');
      }
      return;
    }
    const convertedValue = convertValue(value.trim());
    if (
      editingTag &&
      !tags.filter((_, index) => index !== editingTag.index).includes(convertedValue)
    ) {
      const newTags = [...tags];
      newTags[editingTag.index] = convertedValue;
      setTags(newTags);
      setEditingTag(null);
      // 编辑完成后自动聚焦到 TextArea
      textAreaRef.current?.focus();
    } else {
      message.warning('标签已存在或为空');
    }
  };

  // 取消修改
  const handleEditCancel = () => {
    setEditingTag(null);
    // 取消编辑后自动聚焦到 TextArea
    textAreaRef.current?.focus();
  };

  // 监听 Esc 键取消修改
  const handleEditKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Escape') {
      handleEditCancel();
    }
  };

  useEffect(() => {
    onChange(tags);
  }, [tags]);

  useEffect(() => {
    if (defaultTags && defaultTags.length > 0) {
      if (tagType === 'number') {
        setTags(defaultTags.map((tag) => Number(tag)));
      } else {
        setTags(defaultTags.map((tag) => String(tag)));
      }
    }
  }, [defaultTags, tagType]);

  return (
    <div className={`tag-input-container flex-col ${className}`}>
      <div className="tags-wrapper overflow-auto">
        {tags.map((tag, index) => {
          if (editingTag?.index === index) {
            return (
              <Input
                key={`${index}-${String(tag)}-input`}
                ref={editInputRef}
                defaultValue={editingTag.value}
                onPressEnter={(e) => handleEditConfirm(e.currentTarget.value)}
                onBlur={(e) => handleEditConfirm(e.target.value)}
                onKeyDown={handleEditKeyDown}
                autoFocus
                className="edit-input"
              />
            );
          }

          return (
            <Tag
              key={`${index}-${String(tag)}`}
              closable
              onClose={() => handleTagClose(String(tag))}
              onClick={() => handleTagClick(index, String(tag))}
              className="tag-item truncate"
            >
              {tag}
            </Tag>
          );
        })}
      </div>
      <TextArea
        ref={textAreaRef}
        value={inputValue}
        onChange={handleInputChange}
        onKeyDown={handleTextAreaKeyDown}
        onBlur={handleTextAreaBlur}
        placeholder={placeholder}
        autoSize={{ minRows, maxRows: 6 }} // 自动调整高度
        bordered={false}
        className="tag-textarea"
        style={{ borderRadius: 0 }}
        maxLength={maxLength}
        showCount={showCount}
      />
    </div>
  );
};

export default TagInput;
